package socket1009;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class Client {
    private  OutputStream stream;
    private OutputStreamWriter osw;
    public static Socket socket;
    private BufferedWriter bfw;
    private Scanner scanner=new Scanner(System.in);
    private PrintWriter printWriter;
    public Client() {
        try {
            System.out.println("正在连接");
            socket=new Socket("127.0.0.1",8088);
            System.out.println("连接成功");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    public void start(){
        try {
            stream = socket.getOutputStream();
            osw=new OutputStreamWriter(stream, StandardCharsets.UTF_8);
            bfw=new BufferedWriter(osw);
             printWriter=new PrintWriter(bfw,true);

            System.out.println("请输入对话内容");
           while (true){
               String message=scanner.next();
               if ("exit".equals(message)) {break;}
               printWriter.println(socket.getInetAddress().getHostAddress()+":"+message);

           }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            printWriter.close();
            try {
                stream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }
     static class Reads extends Thread{
        @Override
        public void run() {
            try {
                InputStream stream1 = socket.getInputStream();
                InputStreamReader isr=new InputStreamReader(stream1,StandardCharsets.UTF_8);
                BufferedReader bfr=new BufferedReader(isr);
                String s;
                while ((s = bfr.readLine())!=null){
                    System.out.println(s);
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static void main(String[] args) {
        Client client = new Client();
        Reads reads = new Reads();
        reads.start();
        client.start();

        System.out.println();

    }

}
